package com.jiguang.property.tasks;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiguang.property.dto.NoticeInfoDTO;
import com.jiguang.property.dto.UserInfoDTO;
import com.jiguang.property.entity.*;
import com.jiguang.property.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
@EnableScheduling //启动定时任务
public class ScheduledTasks {
    @Autowired
    private NoticeInfoService noticeInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private HostelInfoService hostelInfoService;
    @Autowired
    private BuildInfoService buildInfoService;
    @Autowired
    private ParkInfoService parkInfoService;
    @Autowired
    private CostInfoService costInfoService;

    //每隔6分钟执行一次
    @Scheduled(fixedRate = 360000)
    public void taskUpdateNotick(){
        //查询今日该发布但未发布的公告
        NoticeInfoDTO noticeInfoDTO = new NoticeInfoDTO();
        noticeInfoDTO.setStatus(0);
        noticeInfoDTO.setEndTime(DateUtil.parse(DateUtil.format(DateUtil.offsetDay(new Date(), 1),"yyyy-MM-dd")));

        List<NoticeInfoDTO> noticeInfoDTOList = (List<NoticeInfoDTO>) noticeInfoService.listByCriteria(noticeInfoDTO).getData().get("noticeInfoDTO");

        if (CollectionUtils.isEmpty(noticeInfoDTOList)){ return;}

        List<NoticeInfo> noticeInfoList = new ArrayList<>();
        for (NoticeInfoDTO infoDTO : noticeInfoDTOList) {
            NoticeInfo noticeInfo = new NoticeInfo();
            //设置未发布状态
            infoDTO.setStatus(1);

            BeanUtils.copyProperties(infoDTO,noticeInfo);
            noticeInfoList.add(noticeInfo);
        }

        noticeInfoService.updateBatchById(noticeInfoList);
    }

    //新增账单（水费，电费，物业费）
    // 每月1号凌晨0点执行
    @Scheduled(cron = "0 0 0 1 * ?")
    public void taskAddCost(){
        //1.获取所有业主
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("is_delete",0);
        userWrapper.eq("position",0);
        List<User> userList = userService.list(userWrapper);

        //获取这个月的日期
        int month = DateUtil.month(new Date()) +1;

        //判断当月是否有生成账单
//        QueryWrapper<CostInfo> costWrapper = new QueryWrapper<>();
//        costWrapper.eq("month",String.valueOf(month));
//        int count = costInfoService.count(costWrapper);
//        if (count > 0){
//            return;
//        }

        if (CollectionUtils.isEmpty(userList)){
            return;
        }

        //根据房屋信息生成水费(每吨2元)，电费(每度1.6元)，物业费(1.20元每平，每月)
        List<CostInfo> costInfos = new ArrayList<>();
        for (User user : userList) {
            //2.获取所有业主的房屋信息以及车位信息
            List<HostelInfo> hostelInfoList = new ArrayList<>();
            List<ParkInfo> parkInfoList = new ArrayList<>();

            //房屋
            QueryWrapper<HostelInfo> hostelWrapper = new QueryWrapper<>();
            hostelWrapper.eq("is_delete",0);
            hostelWrapper.eq("user_id",user.getId());
            hostelInfoList = hostelInfoService.list(hostelWrapper);

            //车位
            QueryWrapper<ParkInfo> parkWrapper = new QueryWrapper<>();
            parkWrapper.eq("is_delete",0);
            parkWrapper.eq("user_id",user.getId());
            parkInfoList = parkInfoService.list(parkWrapper);


            Double propertyManagementFee = 0.0;
            Double waterRate = 0.0;
            Double electricityRate = 0.0;
            String waterRemark = "";
            String propertyManagementFeeRemark = "";
            String electricityRateRemark = "";
            if(!CollectionUtils.isEmpty(hostelInfoList)){
                for (HostelInfo hostelInfo : hostelInfoList) {
                    BuildInfo buildInfo = buildInfoService.getById(hostelInfo.getBuildId());

                    BigDecimal propertyManagementFeeBd = new BigDecimal(Double.toString(propertyManagementFee));
                    BigDecimal waterRateBd = new BigDecimal(Double.toString(waterRate));
                    BigDecimal electricityRateBd = new BigDecimal(Double.toString(electricityRate));

                    Double area = hostelInfo.getArea();
                    propertyManagementFee = propertyManagementFeeBd.add(new BigDecimal(Double.toString(area * 1.2))).doubleValue();
                    propertyManagementFeeRemark = propertyManagementFeeRemark + buildInfo.getBuildingName()+"-"+buildInfo.getUnit()+"-"+hostelInfo.getHostelCode()+"共"+area+"平米\n";

                    waterRate  = waterRateBd.add(new BigDecimal(Double.toString(RandomUtil.randomInt(50,100) * 2.0))).doubleValue();
                    waterRemark = waterRemark + buildInfo.getBuildingName()+"-"+buildInfo.getUnit()+"-"+hostelInfo.getHostelCode()+"共用"+waterRate+"吨水\n";

                    electricityRate  = electricityRateBd.add(new BigDecimal(Double.toString(RandomUtil.randomInt(100,300)* 1.6))).doubleValue();
                    electricityRateRemark = electricityRateRemark + buildInfo.getBuildingName()+"-"+buildInfo.getUnit()+"-"+hostelInfo.getHostelCode()+"共用"+electricityRate+"度水\n";
                }

            }
            if(!"".equals(propertyManagementFeeRemark)){
                propertyManagementFeeRemark = propertyManagementFeeRemark+ "\n" +"每平米收费标准为1.20元\n";
            }


            if (!CollectionUtils.isEmpty(parkInfoList)){
                for (ParkInfo parkInfo : parkInfoList) {
                    BigDecimal propertyManagementFeeBd = new BigDecimal(Double.toString(propertyManagementFee));
                    propertyManagementFee = propertyManagementFeeBd.add(new BigDecimal(Double.toString(16 * 1.0))).doubleValue();
                    propertyManagementFeeRemark = propertyManagementFeeRemark + parkInfo.getLocation()+"-"+parkInfo.getParkingNumber()+"号车位"+"共16平米\n";
                }
            }

            if(!CollectionUtils.isEmpty(parkInfoList)){
                CostInfo costInfo = new CostInfo();
                costInfo.setPrice(propertyManagementFee);
                costInfo.setType("物业费");
                costInfo.setRemark(propertyManagementFeeRemark+ "\n" +"每平米收费标准为1.20元\n");
                costInfo.setUserId(user.getId());
                costInfo.setMonth(String.valueOf(month));
                costInfos.add(costInfo);
            }
            if(!CollectionUtils.isEmpty(hostelInfoList)){
                //水费
                CostInfo costInfoTwo = new CostInfo();

                costInfoTwo.setPrice(waterRate);
                costInfoTwo.setType("水费");
                costInfoTwo.setRemark(waterRemark + "\n"+"每吨收费标准为2元\n");
                costInfoTwo.setUserId(user.getId());
                costInfoTwo.setMonth(String.valueOf(month));
                costInfos.add(costInfoTwo);

                //电费
                CostInfo costInfoThree = new CostInfo();
                costInfoThree.setPrice(electricityRate);
                costInfoThree.setType("电费");
                costInfoThree.setRemark(electricityRateRemark +"\n"+"每度收费标准为1.6元\n");
                costInfoThree.setUserId(user.getId());
                costInfoThree.setMonth(String.valueOf(month));
                costInfos.add(costInfoThree);
            }
        }

        if (!CollectionUtils.isEmpty(costInfos)){
            //生成订单
            costInfoService.saveBatch(costInfos);
        }

    }
}
